package protocol.transactions;

import java.lang.reflect.Type;
import java.util.List;

import protocol.XoneProtocol;
import protocol.XoneServiceCode;
import protocol.meta.AppInfo;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.netease.http.THttpRequest;

import db.manager.ManagerAppInfo;


public class TransactionGetInfoIds extends XoneBaseTransaction {
    /**
     * 0，全部类型；默认值 1，我订阅的；2，我关注的；3，我发布的；
     */
    private int mInfoGroup;
    /**
     * 1，按时间排序，默认值；2，按热度排序；
     */
    private int mSortType;
    private int mAttach;

    public TransactionGetInfoIds(int infoGroup, int sortType, int attach) {
        super(TRANSACTION_TYPE_GETINFOIDS);
        this.mInfoGroup = infoGroup;
        this.mSortType = sortType;
        this.mAttach = attach;
    }

    @Override
    protected void onXoneTransactionSuccess(int code, Object obj) {
        if (obj instanceof JsonElement) {
            String[] infoIds = null;
            try {
                JsonElement array = ((JsonElement)obj).getAsJsonObject().get("infoIds");
                Gson gson = new Gson();
                infoIds = gson.fromJson(array.toString(), String[].class);
                
                array = ((JsonElement)obj).getAsJsonObject().get("infoList");
                List<AppInfo> list = null;
                Type collectionType = new TypeToken<List<AppInfo>>(){}.getType();
                list = gson.fromJson(array, collectionType);
                ManagerAppInfo.delete(mInfoGroup, mSortType);
                if (list.size() > 0 ) {
                    ManagerAppInfo.replaceAppInfo(mInfoGroup, mSortType, list);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            notifyMessage(XoneServiceCode.TRANSACTION_SUCCESS, infoIds);
        }
    }
    
    @Override
    public void onTransact() {
        THttpRequest request = XoneProtocol.getInstance().createGetInfoIdsRequest(mInfoGroup, mSortType, mAttach);
        sendRequest(request);
    }

}
